package com.lantosec.hmrp.modules.eval.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.config.InitDataListener;
import com.lantosec.hmrp.core.kit.PageVO;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.DateUtils;
import com.lantosec.hmrp.modules.eval.entity.EvalDetailedItem;
import com.lantosec.hmrp.modules.eval.entity.EvalEventExtraduty;
import com.lantosec.hmrp.modules.eval.entity.EvalTaskEvent;
import com.lantosec.hmrp.modules.eval.mapper.EvalTaskEventMapper;
import com.lantosec.hmrp.modules.eval.service.IEvalDetailedItemService;
import com.lantosec.hmrp.modules.eval.service.IEvalEventExtradutyService;
import com.lantosec.hmrp.modules.eval.service.IEvalTaskEventService;
import com.lantosec.hmrp.modules.eval.vo.EvalTaskEventVO;
import com.lantosec.hmrp.modules.uploads.entity.SysUploads;
import com.lantosec.hmrp.modules.uploads.service.ISysUploadsService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 考评任务项目事件 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-03-19
 */
@Service
@Primary
@Log4j2
public class EvalTaskEventServiceImpl extends ServiceImpl<EvalTaskEventMapper, EvalTaskEvent> implements IEvalTaskEventService {
    @Autowired
    private ISysUploadsService iSysUploadsService;

    @Autowired
    private IEvalEventExtradutyService iEvalEventExtradutyService;

    @Autowired
    private IEvalDetailedItemService iEvalDetailedItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEvalTaskEvent(EvalTaskEventVO vo) {
        //新增考评任务事件
        EvalTaskEvent evalTaskEvent = vo.convertToEntity();
        //获取当前用户id和名称
        String userId = TokenUtil.getUserId();
        String userName = TokenUtil.getName();
        evalTaskEvent.setCreateUserId(userId);
        evalTaskEvent.setCreateUser(userName);
        evalTaskEvent.setCreateTime(DateUtils.nowDate());
        //当奖惩形式为2是，奖惩值是负数，为1时是正数
        if (evalTaskEvent.getRewardType() == 2) {
            BigDecimal rewardValue = evalTaskEvent.getRewardValue();
            evalTaskEvent.setRewardValue(rewardValue.multiply(new BigDecimal("-1")));
        }
        this.save(evalTaskEvent);
        //更新考评任务明细表的分和钱
        Integer rewardOrientation = evalTaskEvent.getRewardOrientation();
        //查询考评明细表信息
        EvalDetailedItem evalDetailedItem = iEvalDetailedItemService.getById(evalTaskEvent.getEvalDetailedItemId());
        //获得考评项目中所有事件的奖惩值
        BigDecimal rewardValue = baseMapper.getSumItemScore(evalTaskEvent.getEvalDetailedItemId());
        //如果奖惩方向是1，则奖惩值是分
        if (rewardOrientation == 1) {
            //如果项目是分的情况，项目得分=项目标准值+事件奖惩值
            BigDecimal rewardStandard = evalDetailedItem.getRewardStandard();
            rewardValue = rewardStandard.add(rewardValue);
            //如果奖惩形式为奖
            if (evalTaskEvent.getRewardType() == 1) {
                //并且当考评任务明细上限值不为无上限、叠加的奖惩值大于上限时，项目得分为上限值
                if (evalDetailedItem.getRewardUpLimit() != null && rewardValue.compareTo(evalDetailedItem.getRewardUpLimit()) == 1) {
                    rewardValue = evalDetailedItem.getRewardUpLimit();
                }
            }
            //如果奖惩形式为惩
            if (evalTaskEvent.getRewardType() == 2) {
                ////并且当考评任务明细下限值不为无下限、叠加的奖惩值小于下限时，项目得分为下限值
                if (evalDetailedItem.getRewardLowLimit() != null && rewardValue.compareTo(evalDetailedItem.getRewardLowLimit()) == -1) {
                    rewardValue = evalDetailedItem.getRewardLowLimit();
                }
            }
            //更新考评任务详情中的考评项目得分
            evalDetailedItem.setItemScore(rewardValue);
            iEvalDetailedItemService.updateById(evalDetailedItem);
        }
        //如果奖惩方向是2，则奖惩值是钱
        if (rewardOrientation == 2) {
            if (evalTaskEvent.getRewardType() == 1) {
                //并且当考评任务明细上限值不为无上限、叠加的奖惩值大于上限时，项目金额为上限值
                if (evalDetailedItem.getRewardUpLimit() != null && rewardValue.compareTo(evalDetailedItem.getRewardUpLimit()) == 1) {
                    rewardValue = evalDetailedItem.getRewardUpLimit();
                }
            }
            //如果奖惩形式为惩
            if (evalTaskEvent.getRewardType() == 2) {
                ////并且当考评任务明细下限值不为无下限、叠加的奖惩值小于下限时，项目金额为下限值
                if (evalDetailedItem.getRewardLowLimit() != null && rewardValue.compareTo(evalDetailedItem.getRewardLowLimit()) == -1) {
                    rewardValue = evalDetailedItem.getRewardLowLimit();
                }
            }
            //更新考评任务详情中的考评项目得分
            evalDetailedItem.setItemMoney(rewardValue);
            iEvalDetailedItemService.updateById(evalDetailedItem);
        }

        //新增追究责任
        List<EvalEventExtraduty> evalEventExtradutyList = vo.getEvalEventExtradutyList();
        if (null != evalEventExtradutyList && evalEventExtradutyList.size() > 0) {
            evalEventExtradutyList.forEach(parm -> {
                //当奖惩形式为2是，奖惩值是负数，为1时是正数
                if (evalTaskEvent.getRewardType() == 2) {
                    BigDecimal rewardValues = parm.getRewardValue();
                    parm.setRewardValue(rewardValues.multiply(new BigDecimal("-1")));
                }
                parm.setEvalTaskEventId(evalTaskEvent.getEvalTaskEventId());
                iEvalEventExtradutyService.save(parm);
            });
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTaskEvent(String id) {
        //删除事件之后需减项目对应的分和钱
        EvalTaskEvent evalTaskEvent = this.getById(id);
        //获得事件对应项目的id
        Integer evalDetailedItemId = evalTaskEvent.getEvalDetailedItemId();
        //查询项目的信息
        EvalDetailedItem evalDetailedItem = iEvalDetailedItemService.getById(evalDetailedItemId);
        //获得事件是分还是钱
        Integer rewardOrientation = evalTaskEvent.getRewardOrientation();
        //如果事件是分
        if (rewardOrientation == 1) {
            evalDetailedItem.setEvalDetailedItemId(evalDetailedItemId);
            //如果删除的这个事件是项目中最后一个事件，则得分为0
            List<EvalTaskEvent> evalTaskEventList = this.list(new QueryWrapper<EvalTaskEvent>().eq(EvalTaskEvent.ColName.eval_detailed_item_id.toString(), evalDetailedItemId));
            if (evalTaskEventList.size() == 1) {
                BigDecimal score = new BigDecimal(0);
                evalDetailedItem.setItemScore(score);
            } else {
                //查询项目下事件得分总和
                BigDecimal itemScore = baseMapper.getSumItemScore(evalDetailedItemId);
                //项目得分 = 项目总得分 + 项目标准分（项目分）
                BigDecimal rewardStandard = evalDetailedItem.getRewardStandard();
                itemScore = itemScore.add(rewardStandard);
                //如果项目事件是分且事件数>2的情况，项目得分=项目总分-删除事件的得分
                BigDecimal rewardValue = evalTaskEvent.getRewardValue();
                itemScore = itemScore.subtract(rewardValue);
                evalDetailedItem.setItemScore(itemScore);
            }
            iEvalDetailedItemService.updateById(evalDetailedItem);
        }
        //如果事件是钱
        if (rewardOrientation == 2) {
            evalDetailedItem.setEvalDetailedItemId(evalDetailedItemId);
            //得到项目下事件的总金额
            BigDecimal itemMoney = baseMapper.getSumItemScore(evalDetailedItemId);
            //项目金额=项目总金额-删除事件的金额
            BigDecimal rewardValue = evalTaskEvent.getRewardValue();
            itemMoney = itemMoney.subtract(rewardValue);
            //如果是奖
            if (evalTaskEvent.getRewardType() == 1) {
                //如果事件项目总金额大于上限，取上限值
                if (evalDetailedItem.getRewardUpLimit() != null && itemMoney.compareTo(evalDetailedItem.getRewardUpLimit()) == 1) {
                    itemMoney = evalDetailedItem.getRewardUpLimit();
                }
            }
            //如果奖惩形式为惩
            if (evalTaskEvent.getRewardType() == 2) {
                ////并且当考评任务明细下限值不为无下限、叠加的奖惩值小于下限时，项目金额为下限值
                if (evalDetailedItem.getRewardLowLimit() != null && itemMoney.compareTo(evalDetailedItem.getRewardLowLimit()) == -1) {
                    itemMoney = evalDetailedItem.getRewardLowLimit();
                }
            }
            //如果删除的这个事件是项目中最后一个事件，则金额为0
            List<EvalTaskEvent> evalTaskEventList = this.list(new QueryWrapper<EvalTaskEvent>().eq(EvalTaskEvent.ColName.eval_detailed_item_id.toString(), evalDetailedItemId));
            if (evalTaskEventList.size() == 1) {
                BigDecimal money = new BigDecimal(0);
                evalDetailedItem.setItemMoney(money);
            } else {
                evalDetailedItem.setItemMoney(itemMoney);
            }
            iEvalDetailedItemService.updateById(evalDetailedItem);
        }
        //删除事件表
        this.removeById(id);
        //删除追究责任
        iEvalEventExtradutyService.remove(new QueryWrapper<EvalEventExtraduty>().eq(EvalEventExtraduty.ColName.eval_task_event_id.toString(), id));

    }

    @Override
    public List<EvalTaskEventVO> queryItemHistoryTask(String startDate, String endDate, Integer evalDetailedId, String evalItemId, Integer planTargetId) {
        //查询出考评项目的历史事件
        List<EvalTaskEventVO> evalTaskEventVOList = baseMapper.getEvalTaskEventVoList(startDate, endDate, evalDetailedId, evalItemId, planTargetId);
        //添加事件中的追究责任和事件图片
        evalTaskEventVOList = getEvalTaskEventListVo(evalTaskEventVOList);
        return evalTaskEventVOList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageVO<EvalTaskEventVO> queryTargetTask(PageVO<EvalTaskEvent> page, String evalDetailedId) {
        //查询考评对象下的所有的事件列表
        PageVO<EvalTaskEventVO> evalTaskEventVOPageVO = new PageVO<>();
        PageVO<EvalTaskEvent> evalTaskEventPageVO = this.page(page, new QueryWrapper<EvalTaskEvent>().eq(EvalTaskEvent.ColName.eval_detailed_id.toString(), evalDetailedId)
                .orderByDesc(EvalTaskEvent.ColName.create_time.toString()));
        List<EvalTaskEvent> evalTaskEventList = evalTaskEventPageVO.getRecords();
        List<EvalTaskEventVO> evalTaskEventVOList = new ArrayList<>();
        //查询事件下的追加事项
        evalTaskEventList.forEach(parm -> {
            EvalTaskEventVO evalTaskEventVO = new EvalTaskEventVO();
            Integer evalTaskEventId = parm.getEvalTaskEventId();
            List<EvalEventExtraduty> evalEventExtradutyList = iEvalEventExtradutyService.list(new QueryWrapper<EvalEventExtraduty>().eq(EvalEventExtraduty.ColName.eval_task_event_id.toString(), evalTaskEventId));
            if (null != evalEventExtradutyList && evalEventExtradutyList.size() > 0) {
                evalTaskEventVO.setEvalEventExtradutyList(evalEventExtradutyList);
            }
            evalTaskEventVOList.add(evalTaskEventVO);
        });
        evalTaskEventVOPageVO.setRecords(evalTaskEventVOList);
        evalTaskEventVOPageVO.setPageSize(evalTaskEventPageVO.getPageSize());
        evalTaskEventVOPageVO.setTotal(evalTaskEventPageVO.getTotal());
        evalTaskEventVOPageVO.setPageNo(evalTaskEventPageVO.getPageNo());
        return evalTaskEventVOPageVO;
    }

    @Override
    public PageVO<EvalTaskEventVO> getEvalTaskEvent(PageVO<EvalTaskEvent> page, String evalDetailedId) {
        //获得当前用户ID
        String userId = TokenUtil.getUserId();
        //查询审核项目的管理人是当前用户的审核列表
        PageVO<EvalTaskEventVO> eventVOPageVO = baseMapper.getEvalTaskEvent(evalDetailedId,userId);
        List<EvalTaskEventVO> evalTaskEventVOList = eventVOPageVO.getRecords();
        evalTaskEventVOList.forEach(param -> {
            //返回图片路径
            String evidencePhotoList = param.getEvidencePhotoList();
            param = getSavePath(param, evidencePhotoList);
        });
        return eventVOPageVO;
    }

    @Override
    public void evalTaskEventCommit(List<EvalTaskEventVO> voList) {
        String userId = TokenUtil.getUserId();
        String name = TokenUtil.getName();
        if(CollectionUtils.isNotEmpty(voList)){
            voList.forEach(param->{
                EvalTaskEvent evalTaskEvent = param.convertToEntity();
                evalTaskEvent.setReviewUserId(userId);
                evalTaskEvent.setReviewUser(name);
                evalTaskEvent.setReviewTime(DateUtils.nowDate());
                this.updateById(evalTaskEvent);
            });
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public List<EvalTaskEventVO> getEvalTaskEventListVo(List<EvalTaskEventVO> evalTaskEventVOList) {
        evalTaskEventVOList.forEach(parm -> {
            String evidencePhotoList = parm.getEvidencePhotoList();
            parm = getSavePath(parm, evidencePhotoList);
            //查询考评事件下的责任
            Integer evalTaskEventId = parm.getEvalTaskEventId();
            List<EvalEventExtraduty> evalEventExtradutyList = iEvalEventExtradutyService.list(new QueryWrapper<EvalEventExtraduty>()
                    .eq(EvalEventExtraduty.ColName.eval_task_event_id.toString(), evalTaskEventId));
            parm.setEvalEventExtradutyList(evalEventExtradutyList);
        });
        return evalTaskEventVOList;
    }

    private EvalTaskEventVO getSavePath(EvalTaskEventVO param, String evidencePhotoList) {
        if (StringUtils.isNotEmpty(evidencePhotoList)) {
            String[] evidencePhoto = evidencePhotoList.split(",");
            List list = new ArrayList();
            for (String s : evidencePhoto) {
                try {
                    SysUploads sysUploads = iSysUploadsService.getById(s);
                    String savePath = sysUploads.getSavePath();
                    String fileName = sysUploads.getFileName();
                    list.add(InitDataListener.uploadsUrl + savePath + fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            param.setSavePath(list);
        }
        return param;
    }
}
